package com.minhua.jijiehao2.mainframe.launcher.registeractivity.impl

import android.content.Context
import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.minhua.jijiehao2.R
import com.minhua.jijiehao2.base.BaseActivity
import com.minhua.jijiehao2.constants.DefineKey
import com.minhua.jijiehao2.mainframe.launcher.finalregisteractivity.impl.FinalRegisterActivity
import com.minhua.jijiehao2.mainframe.launcher.registeractivity.imp.IRegisterView
import com.minhua.jijiehao2.utils.T
import kotlinx.android.synthetic.main.activity_register.*

internal class RegisterActivity : BaseActivity<IRegisterView, RegisterPresenter>(), IRegisterView {
    override fun getLayoutId(): Int = R.layout.activity_register

    override fun getPresenter(): RegisterPresenter = RegisterPresenter()

    private val onClickListener: View.OnClickListener = View.OnClickListener { v ->
        when (v.id) {
            R.id.ivBack -> finish()
            R.id.tvNext -> FinalRegisterActivity.intentStart(this, getUserName(), getCheckCode())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        code.endTimer()
    }

    private val textWatcher: TextWatcher = object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            tvNext.isEnabled = !(TextUtils.isEmpty(phone.text) || TextUtils.isEmpty(code.text))
        }

    }

    companion object {
        fun intentStart(context: Context, phone: String) {
            val intent = Intent(context, RegisterActivity::class.java)
            intent.putExtra(DefineKey.PHONE, phone)
            context.startActivity(intent)
        }
    }

    override fun initView() {
        val stringExtra = intent.getStringExtra(DefineKey.PHONE)
        if (!TextUtils.isEmpty(stringExtra)) {
            phone.editText.setText(stringExtra)
        }
        phone.editText.addTextChangedListener(textWatcher)
        code.editText.addTextChangedListener(textWatcher)

        tvNext.setOnClickListener(onClickListener)
        ivBack.setOnClickListener(onClickListener)

        code.setOnCodeSendListener { mPresenter.sendCode() }
    }

    override fun getUserName(): String = phone.text

    override fun getCheckCode(): String = code.text


    override fun onUserNameError() {
        T.showShort("请输入正确的手机号")
    }

    override fun onCheckCodeError() {
        T.showShort("验证码错误")
    }

    override fun onSendCodeSuccess(message: String) {
        T.showShort(message)
        code.startTimer()
    }
}
